$(document).ready(function() {
	$.get(chrome.runtime.getURL("manifest.json"), function(info) {
		document.title = "导出历史浏览记录 v" + info.version;
		$("#eh-title").text("导出历史浏览记录 v" + info.version);
	});

	const searchHistory = function(query) {
		return new Promise(function(resolve) {
			chrome.history.search(query, function(historyItems) {
				resolve(historyItems);
			});
		});
	}

	const getHistoryVisits = function(details) {
		return new Promise(function(resolve) {
			chrome.history.getVisits(details, function(visitItems) {
				resolve(visitItems);
			});
		});
	}

	var now = new Date();
	var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
	
	var publishDate = new Date(2008, 12-1, 11);
	var publishTime = publishDate.getTime();

	var dayMs = 24 * 60 * 60 * 1000;
	dayTime = today.getTime();
	
	$(async function() {
		while (dayTime != publishTime) {
			var dayEndTime = dayTime + dayMs - 1;
			var historyItems = await searchHistory({startTime: dayTime, endTime: dayEndTime, maxResults: 10000, text: ""});
			var arr = [];

			for (var historyItem of historyItems) {
				visitItems = await getHistoryVisits({url: historyItem.url});
				for (var visitItem of visitItems) {
					if (visitItem.visitTime>=dayTime && visitItem.visitTime<=dayEndTime) {
						arr.push({title: historyItem.title, url: historyItem.url, time: visitItem.visitTime});
					}
				}
			}
			
			arr.sort(function(item1, item2) {
				return item1.time - item2.time;
			});
			arr.reverse();
			
			if (arr.length > 0) {
				var theDate = new Date(dayTime);

				$("#eh-content").append("<h2>" + theDate.getFullYear() + "年" + (theDate.getMonth() + 1) + "月" + theDate.getDate() + "日" + "</h2>\n");
				
				for (var item of arr) {
					$("#eh-content").append("<p>[" + new Date(item.time).toLocaleString() + "] " + item.title + " " + "<a href=\"" + item.url + "\">" + item.url + "</a></p>\n");
				}
			}

			dayTime -= dayMs;
		}
		$("#eh-done").css("display","").css("visibility","");
	});

	$("#eh-save").click(function() {
		const now = new Date();

		const year = now.getFullYear();
		const month = ("0" + (now.getMonth() + 1)).slice(-2);
		const day = ("0" + now.getDate()).slice(-2);
		const hours = ("0" + now.getHours()).slice(-2);
		const minutes = ("0" + now.getMinutes()).slice(-2);
		const seconds = ("0" + now.getSeconds()).slice(-2);

		const formattedTime = year + month + day + hours + minutes + seconds;

		var prefix = '<html>\n<head><meta charset="UTF-8"><title>导出的历史浏览记录</title><base target="_blank"></head>\n<body><h1>导出的历史浏览记录</h1>\n' +
			'<p class="info">' + now + ' <a target="_blank" href="https://gitee.com/milaoshu1020/exporthistory">[项目地址]</a></p>\n';
		var suffix = "</body>\n</html>\n"

		var file = new File([prefix + $("#eh-content").html() + suffix],"导出的历史浏览记录"+formattedTime+".html",{type: "text/plain;charset=utf-8"});
		saveAs(file);

		return false;
	});
});
